#include "stdafx.h"
#include "../core/DebugManager.h"

namespace ja2
{
	DebugManager::DebugManager(boost::filesystem::path const &WorkingPath)
		: m_Log((WorkingPath / "debug.txt").string(), std::ios_base::trunc), m_RecordToFile(false), m_RecordToDebugger(false)
	{
	}

	bool DebugManager::topic_enabled(Topic TopicId) const
	{
		if(topic_exists(TopicId))
			return m_Topics.find(TopicId)->second;

		return false;
	}

	void DebugManager::debug_message(const char *SourceFile, long LineNum, const char *String)
	{
		
		// Build the output string
		std::string const out_string = (boost::format("{ %ld } %s [Line %d in %s]\n") % boost::posix_time::to_simple_string(boost::posix_time::microsec_clock::local_time()) % String % LineNum % SourceFile).str();
		// Output to debugger
		if(m_RecordToDebugger)
			std::cout << out_string.c_str() << std::endl;
		// Record to file if required
		if(m_RecordToFile)
		{
			assert(m_Log.is_open());
			m_Log << out_string;
			m_Log.flush();
		}
	}

	void DebugManager::debug_message_real(Topic TopicId, DebugLevel /*Level*/, const char *Message)
	{
		// Check for a registered topic ID
		if(topic_exists(TopicId))
		{
			std::cout << Message << std::endl;
			// Record to file if required
			if(m_RecordToFile)
			{
				assert(m_Log.is_open());
				m_Log << Message;
				m_Log.flush();
			}
		}
	}

	void DebugManager::assert_message(const char *Condition, const char *Message, long LineNum, const char *FunctionName, const char *SourceFileName)
	{
		std::ostringstream basic_information;
		basic_information << "{ " << GetTickCount() << " } Assertion failed (" << Condition << ")";
		// Message exist
		if(Message != nullptr)
			basic_information << ": " << Message;
		basic_information << " [Line " << LineNum;
		// Function name valid
		if(FunctionName != nullptr)
			basic_information << " in function " << FunctionName;
		basic_information << " in file " << SourceFileName << "]";
		// Output to debugger
		if(m_RecordToDebugger)
			std::cout << basic_information.str() << std::endl;
		assert(!Condition);
//		debug_message( TOPIC_GAME, DBG_LEVEL_1, outputString.str().c_str());
	}

	void DebugManager::register_debug_topic(RegisterCommand Command, Topic TopicId, const char *Message)
	{
		switch(Command)
		{
		case RC_ADD:
			assert(!topic_exists(TopicId));
			m_Topics[TopicId] = true;
			debug_message_real(TopicId, DL_0, Message);
			break;
		case RC_REMOVE:
			assert(topic_exists(TopicId));
			debug_message_real(TopicId, DL_0, Message);
			m_Topics.erase(m_Topics.find(TopicId));
			break;
		}
	}

	bool DebugManager::topic_exists(Topic TopicId) const
	{
		return (m_Topics.count(TopicId) == 1);
	}

	void DebugManager::clear_all_topics()
	{
		m_Topics.clear();
	}
} /*ja2*/